import {events} from "./types";
import {ClientTypes, SocketManager} from "../index";
import {WrapperClients} from "./route";

const consola = require('consola');

export class ClientManager {
    public readonly context: any;
    public readonly socket: any;
    public readonly client: any;
    public readonly query: any;
    public readonly clientType: ClientTypes;
    public readonly id: string;
    public readonly server: SocketManager;
    public accountId: string = "";
    public lKey: string = "";
    public readonly app: any;

    constructor(context: any, server: SocketManager) {
        this.app = server.app;
        const client = context.socket;
        const handshake = client.handshake;
        const {query, headers} = handshake;
        this.clientType = query.client_type;
        this.accountId = query.account_id;
        this.socket = client;
        this.client = client;
        context.manager = this;
        this.context = context;
        this.query = query;
        this.id = client.id;
        this.server = server;
        consola.info(`客户端: ${client.id} 进入了服务器，信息：${JSON.stringify(query)} `);
        this.init();
    }

    init() {
        const client = this.socket;
        client.on('disconnect', () => {
            this.server.removeClient(this.id)
        });

        client.on('broadcast', () => {
            consola.info("收到广播");
        });

        client.on(events.PONG, () => {

        });
        if (this.clientType === ClientTypes.oasis_client) {
            WrapperClients(this);
        }
        client.broadcast.emit('client.in', {client: client.id});
    }

    //oasis
    public getOasisSign(str: string) {
        return new Promise(((resolve, reject) => {
            this.socket.emit('sign', str, (data) => {
                resolve(data);
            });
        }));
    }
}



